import request from '@/util/request';
import type { FileItem, UploadResponse } from '@/types/note/file';
// import { SignUtil } from '@/util/signin';

// 上传文件
export const uploadFile = (file: File, path: string = '', userId: number) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('path', path || '');
    formData.append('userId', userId.toString());

    return request.post<UploadResponse>('/api/minio/upload', formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
            // 'Authorization': SignUtil.getAccessToken()
        }
    });
};

// 下载文件
export const downloadFile = async (attachmentId: string, userId: number, fileName: string) => {
    try {
        const response = await request.get('/api/minio/download', {
            params: {
                attachmentId,
                userId
            },
            responseType: 'blob',
            headers: {
                // 'Authorization': SignUtil.getAccessToken(),
            }
        });

        // 创建下载链接
        const blob = new Blob([response.data])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        return response;
    } catch (error) {
        console.error('Download error:', error);
        throw error;
    }
};

// 使用 type 关键字定义本地接口
type FileResponse = {
    size: number;
    name: string;
    etag: string;
    attachmentId: number;
    uploadTime: string;
    url: string;
    fileType: string;
    order: number;
}

// 修改获取文件列表方法
export const getFileList = async (prefix: string = '', userId: number) => {
    try {
        const response = await request.get<FileResponse[]>('/api/minio/list', {
            params: {
                prefix,
                userId
            }
        });
        return response.data;
    } catch (error) {
        console.error('Get file list error:', error);
        throw error;
    }
};

// 删除文件
export const deleteFile = (attachmentId: string, userId: number) => {
    return request.delete('/api/minio/delete', {
        params: {
            attachmentId,
            userId
        }
    });
};

// 预览文件
export const previewFileApi = (attachmentId: string, userId: number) => {
    return request.get('/api/minio/preview', {
        params: {
            attachmentId,
            userId
        },
        responseType: 'blob'
    });
};

// 创建文件夹
export const createFolder = (path: string, userId: number) => {
    return request.post('/api/minio/mkdir', null, {
        params: {
            path,
            userId
        }
    });
};

// 批量下载文件
export const batchDownloadFiles = async (files: FileItem[], userId: number) => {
    for (const file of files) {
        await downloadFile(file.id, userId, file.name);
    }
};

// 批量删除文件
export const batchDeleteFiles = async (files: FileItem[], userId: number) => {
    for (const file of files) {
        await deleteFile(file.id, userId);
    }
};

// 获取文件预览URL
// export const getPreviewUrl = (attachmentId: string, userId: number) => {
//     return `/api/minio/preview?attachmentId=${attachmentId}&userId=${userId}`;
// };

// 生成分享链接（模拟）
export const generateShareLink = (fileId: string) => {
    return {
        shareUrl: `http://qb.sso.com:6677/share/${fileId}`,
        shareCode: Math.random().toString(36).substring(2, 8).toUpperCase()
    };
}; 